<template>
  <el-dialog
    :model-value="visible"
    @update:model-value="$emit('close')"
    title="数据清理"
    width="700px"
    :close-on-click-modal="false"
  >
    <div class="cleanup-container">
      <!-- 清理选项 -->
      <div class="cleanup-options">
        <h4>清理选项</h4>
        <div class="options-list">
          <el-card class="option-item">
            <div class="option-header">
              <el-checkbox v-model="cleanupOptions.duplicates">
                重复账号 ({{ duplicateAccounts.length }} 个)
              </el-checkbox>
              <el-button size="small" type="text" @click="previewDuplicates">预览</el-button>
            </div>
            <div class="option-desc">删除完全相同的账号记录</div>
          </el-card>

          <el-card class="option-item">
            <div class="option-header">
              <el-checkbox v-model="cleanupOptions.emptyAccounts">
                空账号 ({{ emptyAccounts.length }} 个)
              </el-checkbox>
              <el-button size="small" type="text" @click="previewEmpty">预览</el-button>
            </div>
            <div class="option-desc">删除缺少关键信息的账号</div>
          </el-card>

          <el-card class="option-item">
            <div class="option-header">
              <el-checkbox v-model="cleanupOptions.oldAccounts">
                过期账号 ({{ oldAccounts.length }} 个)
              </el-checkbox>
              <el-button size="small" type="text" @click="previewOld">预览</el-button>
            </div>
            <div class="option-desc">删除超过1年未使用的账号</div>
          </el-card>

          <el-card class="option-item">
            <div class="option-header">
              <el-checkbox v-model="cleanupOptions.weakPasswords">
                弱密码账号 ({{ weakPasswordAccounts.length }} 个)
              </el-checkbox>
              <el-button size="small" type="text" @click="previewWeak">预览</el-button>
            </div>
            <div class="option-desc">标记或删除使用弱密码的账号</div>
          </el-card>
        </div>
      </div>

      <!-- 清理统计 -->
      <div class="cleanup-stats">
        <h4>清理统计</h4>
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-number">{{ totalIssues }}</div>
            <div class="stat-label">问题总数</div>
          </div>
          <div class="stat-card">
            <div class="stat-number">{{ selectedIssues }}</div>
            <div class="stat-label">待清理</div>
          </div>
          <div class="stat-card">
            <div class="stat-number">{{ cleanupSavings }}</div>
            <div class="stat-label">节省空间</div>
          </div>
        </div>
      </div>

      <!-- 高级选项 -->
      <div class="advanced-options">
        <h4>高级选项</h4>
        <div class="advanced-controls">
          <el-checkbox v-model="backupBeforeCleanup">
            清理前自动备份
          </el-checkbox>
          <el-checkbox v-model="moveToTrash">
            移至回收站而非直接删除
          </el-checkbox>
          <el-checkbox v-model="showDetailedLog">
            显示详细清理日志
          </el-checkbox>
        </div>
      </div>

      <!-- 预览区域 -->
      <div v-if="previewData.length > 0" class="preview-section">
        <div class="preview-header">
          <h4>{{ previewTitle }}</h4>
          <el-button size="small" @click="closePreview">关闭预览</el-button>
        </div>
        <div class="preview-list">
          <div
            v-for="account in previewData"
            :key="account.id"
            class="preview-item"
          >
            <div class="account-info">
              <div class="account-name">{{ account.name }}</div>
              <div class="account-details">{{ account.username }} | {{ getCategoryName(account.category) }}</div>
              <div class="account-reason" v-if="account.reason">{{ account.reason }}</div>
            </div>
            <div class="account-actions">
              <el-button size="small" type="text" @click="excludeFromCleanup(account)">
                排除
              </el-button>
            </div>
          </div>
        </div>
      </div>
    </div>

    <template #footer>
      <div class="dialog-footer">
        <el-button @click="$emit('close')">取消</el-button>
        <el-button 
          type="danger" 
          @click="performCleanup"
          :disabled="!hasSelection"
          :loading="isClearing"
        >
          {{ isClearing ? '清理中...' : '开始清理' }}
        </el-button>
      </div>
    </template>

    <!-- 清理结果对话框 -->
    <el-dialog
      v-model="showResultDialog"
      title="清理完成"
      width="500px"
      append-to-body
    >
      <div class="cleanup-result">
        <div class="result-summary">
          <el-icon size="40" color="#67C23A"><SuccessFilled /></el-icon>
          <div class="result-text">
            <div class="result-title">清理完成！</div>
            <div class="result-desc">共清理了 {{ cleanupResult.cleaned }} 项数据</div>
          </div>
        </div>
        
        <div class="result-details">
          <div v-for="(count, type) in cleanupResult.details" :key="type" class="detail-item">
            <span class="detail-label">{{ getCleanupTypeName(type) }}：</span>
            <span class="detail-count">{{ count }} 项</span>
          </div>
        </div>

        <div v-if="cleanupResult.log" class="cleanup-log">
          <h5>清理日志</h5>
          <div class="log-content">
            <div v-for="(logItem, index) in cleanupResult.log" :key="index" class="log-item">
              {{ logItem }}
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </el-dialog>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useAccountsStore } from '../stores/accounts'
import { ElMessage, ElMessageBox } from 'element-plus'
import { SuccessFilled } from '@element-plus/icons-vue'
import zxcvbn from 'zxcvbn'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['close'])

const accountsStore = useAccountsStore()
const cleanupOptions = ref({
  duplicates: false,
  emptyAccounts: false,
  oldAccounts: false,
  weakPasswords: false
})

const backupBeforeCleanup = ref(true)
const moveToTrash = ref(true)
const showDetailedLog = ref(false)
const isClearing = ref(false)
const showResultDialog = ref(false)
const cleanupResult = ref({})

const previewData = ref([])
const previewTitle = ref('')
const excludedItems = ref(new Set())

// 分析需要清理的数据
const duplicateAccounts = computed(() => {
  const seen = new Map()
  const duplicates = []
  
  accountsStore.accounts.forEach(account => {
    const key = `${account.name || ''}_${account.username || ''}_${account.url || ''}`
    if (seen.has(key)) {
      duplicates.push({
        ...account,
        reason: '与其他账号重复'
      })
    } else {
      seen.set(key, account)
    }
  })
  
  return duplicates.filter(account => !excludedItems.value.has(account.id))
})

const emptyAccounts = computed(() => {
  return accountsStore.accounts.filter(account => {
    if (excludedItems.value.has(account.id)) return false
    
    const isEmpty = !account.name?.trim() || 
                   !account.username?.trim() || 
                   !account.password?.trim()
    
    if (isEmpty) {
      account.reason = '缺少关键信息（名称、用户名或密码）'
    }
    
    return isEmpty
  })
})

const oldAccounts = computed(() => {
  const oneYearAgo = new Date()
  oneYearAgo.setFullYear(oneYearAgo.getFullYear() - 1)
  
  return accountsStore.accounts.filter(account => {
    if (excludedItems.value.has(account.id)) return false
    
    const lastUsed = account.lastUsed ? new Date(account.lastUsed) : new Date(account.createdAt || Date.now())
    const isOld = lastUsed < oneYearAgo
    
    if (isOld) {
      account.reason = `超过1年未使用（最后使用：${lastUsed.toLocaleDateString()}）`
    }
    
    return isOld
  })
})

const weakPasswordAccounts = computed(() => {
  return accountsStore.accounts.filter(account => {
    if (excludedItems.value.has(account.id)) return false
    
    if (!account.password) return false
    
    const result = zxcvbn(account.password)
    const isWeak = result.score <= 1
    
    if (isWeak) {
      account.reason = `密码强度过弱（评分：${result.score}/4）`
    }
    
    return isWeak
  })
})

// 统计信息
const totalIssues = computed(() => 
  duplicateAccounts.value.length + 
  emptyAccounts.value.length + 
  oldAccounts.value.length + 
  weakPasswordAccounts.value.length
)

const selectedIssues = computed(() => {
  let count = 0
  if (cleanupOptions.value.duplicates) count += duplicateAccounts.value.length
  if (cleanupOptions.value.emptyAccounts) count += emptyAccounts.value.length
  if (cleanupOptions.value.oldAccounts) count += oldAccounts.value.length
  if (cleanupOptions.value.weakPasswords) count += weakPasswordAccounts.value.length
  return count
})

const cleanupSavings = computed(() => {
  const avgAccountSize = 500 // 估算每个账号平均占用500字节
  const totalSize = selectedIssues.value * avgAccountSize
  
  if (totalSize < 1024) return totalSize + ' B'
  if (totalSize < 1024 * 1024) return Math.round(totalSize / 1024) + ' KB'
  return Math.round(totalSize / (1024 * 1024)) + ' MB'
})

const hasSelection = computed(() => 
  Object.values(cleanupOptions.value).some(option => option)
)

// 预览功能
const previewDuplicates = () => {
  previewData.value = duplicateAccounts.value
  previewTitle.value = '重复账号预览'
}

const previewEmpty = () => {
  previewData.value = emptyAccounts.value
  previewTitle.value = '空账号预览'
}

const previewOld = () => {
  previewData.value = oldAccounts.value
  previewTitle.value = '过期账号预览'
}

const previewWeak = () => {
  previewData.value = weakPasswordAccounts.value
  previewTitle.value = '弱密码账号预览'
}

const closePreview = () => {
  previewData.value = []
  previewTitle.value = ''
}

const excludeFromCleanup = (account) => {
  excludedItems.value.add(account.id)
  previewData.value = previewData.value.filter(item => item.id !== account.id)
  ElMessage.success(`已排除账号：${account.name}`)
}

// 获取分类名称
const getCategoryName = (category) => {
  const categoryMap = {
    work: '工作',
    personal: '个人',
    social: '社交媒体',
    finance: '金融理财',
    entertainment: '游戏娱乐',
    shopping: '购物网站'
  }
  return categoryMap[category] || '其他'
}

// 获取清理类型名称
const getCleanupTypeName = (type) => {
  const typeMap = {
    duplicates: '重复账号',
    emptyAccounts: '空账号',
    oldAccounts: '过期账号',
    weakPasswords: '弱密码账号'
  }
  return typeMap[type] || type
}

// 执行清理
const performCleanup = async () => {
  try {
    const result = await ElMessageBox.confirm(
      `确定要清理 ${selectedIssues.value} 项数据吗？此操作不可撤销。`,
      '确认清理',
      {
        confirmButtonText: '确认清理',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    if (result === 'confirm') {
      isClearing.value = true
      
      // 备份数据（如果启用）
      if (backupBeforeCleanup.value) {
        await createBackup()
      }
      
      const cleanupLog = []
      const cleanupDetails = {}
      let totalCleaned = 0
      
      // 执行各种清理操作
      if (cleanupOptions.value.duplicates) {
        const cleaned = await cleanupDuplicates()
        cleanupDetails.duplicates = cleaned
        totalCleaned += cleaned
        cleanupLog.push(`清理重复账号：${cleaned} 项`)
      }
      
      if (cleanupOptions.value.emptyAccounts) {
        const cleaned = await cleanupEmptyAccounts()
        cleanupDetails.emptyAccounts = cleaned
        totalCleaned += cleaned
        cleanupLog.push(`清理空账号：${cleaned} 项`)
      }
      
      if (cleanupOptions.value.oldAccounts) {
        const cleaned = await cleanupOldAccounts()
        cleanupDetails.oldAccounts = cleaned
        totalCleaned += cleaned
        cleanupLog.push(`清理过期账号：${cleaned} 项`)
      }
      
      if (cleanupOptions.value.weakPasswords) {
        const cleaned = await handleWeakPasswords()
        cleanupDetails.weakPasswords = cleaned
        totalCleaned += cleaned
        cleanupLog.push(`处理弱密码账号：${cleaned} 项`)
      }
      
      // 显示结果
      cleanupResult.value = {
        cleaned: totalCleaned,
        details: cleanupDetails,
        log: showDetailedLog.value ? cleanupLog : null
      }
      
      showResultDialog.value = true
      
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('清理失败:', error)
      ElMessage.error('清理失败，请重试')
    }
  } finally {
    isClearing.value = false
  }
}

// 清理重复账号
const cleanupDuplicates = async () => {
  let cleaned = 0
  for (const account of duplicateAccounts.value) {
    await accountsStore.deleteAccount(account.id)
    cleaned++
  }
  return cleaned
}

// 清理空账号
const cleanupEmptyAccounts = async () => {
  let cleaned = 0
  for (const account of emptyAccounts.value) {
    await accountsStore.deleteAccount(account.id)
    cleaned++
  }
  return cleaned
}

// 清理过期账号
const cleanupOldAccounts = async () => {
  let cleaned = 0
  for (const account of oldAccounts.value) {
    await accountsStore.deleteAccount(account.id)
    cleaned++
  }
  return cleaned
}

// 处理弱密码账号（标记而非删除）
const handleWeakPasswords = async () => {
  let handled = 0
  for (const account of weakPasswordAccounts.value) {
    // 在备注中添加弱密码标记
    const updatedAccount = {
      ...account,
      notes: (account.notes || '') + '\n[系统标记：弱密码，建议更新]',
      updatedAt: new Date().toISOString()
    }
    await accountsStore.updateAccount(account.id, updatedAccount)
    handled++
  }
  return handled
}

// 创建备份
const createBackup = async () => {
  try {
    const backupData = {
      backupInfo: {
        date: new Date().toISOString(),
        type: 'cleanup_backup',
        reason: 'Auto backup before cleanup'
      },
      accounts: accountsStore.accounts
    }
    
    const blob = new Blob([JSON.stringify(backupData, null, 2)], { type: 'application/json' })
    const url = URL.createObjectURL(blob)
    const a = document.createElement('a')
    a.href = url
    a.download = `cleanup_backup_${new Date().toISOString().split('T')[0]}.json`
    a.click()
    URL.revokeObjectURL(url)
    
  } catch (error) {
    console.error('备份失败:', error)
    throw new Error('备份失败')
  }
}

onMounted(() => {
  // 组件挂载时重置排除列表
  excludedItems.value.clear()
})
</script>

<style scoped>
.cleanup-container {
  display: flex;
  flex-direction: column;
  gap: 24px;
}

.cleanup-container h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
  font-weight: 600;
}

.options-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.option-item {
  padding: 16px;
}

.option-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.option-desc {
  font-size: 12px;
  color: #666;
  margin-left: 24px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  gap: 16px;
}

.stat-card {
  text-align: center;
  padding: 20px;
  background: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #e9ecef;
}

.stat-number {
  font-size: 24px;
  font-weight: bold;
  color: #333;
  margin-bottom: 8px;
}

.stat-label {
  font-size: 14px;
  color: #666;
}

.advanced-options {
  padding: 16px;
  background: #f0f9ff;
  border: 1px solid #bfdbfe;
  border-radius: 8px;
}

.advanced-controls {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.preview-section {
  border: 1px solid #e6e6e6;
  border-radius: 8px;
  overflow: hidden;
}

.preview-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #f8f9fa;
  border-bottom: 1px solid #e6e6e6;
}

.preview-header h4 {
  margin: 0;
}

.preview-list {
  max-height: 300px;
  overflow-y: auto;
}

.preview-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  border-bottom: 1px solid #f0f0f0;
}

.preview-item:last-child {
  border-bottom: none;
}

.account-info {
  flex: 1;
}

.account-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.account-details {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.account-reason {
  font-size: 11px;
  color: #e53e3e;
  background: #fed7d7;
  padding: 2px 6px;
  border-radius: 3px;
  display: inline-block;
}

.cleanup-result {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.result-summary {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #f0f9ff;
  border-radius: 8px;
}

.result-text {
  flex: 1;
}

.result-title {
  font-size: 18px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.result-desc {
  color: #666;
}

.result-details {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.detail-item {
  display: flex;
  justify-content: space-between;
  padding: 8px 16px;
  background: #f8f9fa;
  border-radius: 4px;
}

.detail-label {
  color: #666;
}

.detail-count {
  font-weight: 500;
  color: #333;
}

.cleanup-log {
  border-top: 1px solid #e6e6e6;
  padding-top: 16px;
}

.cleanup-log h5 {
  margin: 0 0 12px 0;
  color: #333;
}

.log-content {
  max-height: 200px;
  overflow-y: auto;
  background: #f8f9fa;
  padding: 12px;
  border-radius: 4px;
}

.log-item {
  font-size: 12px;
  color: #666;
  margin-bottom: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style>
